package com.sigmatrix.h5.auth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.sigmatrix.h5.web.Result;

/**
 * 请求权限拦截。
 * 
 * @author wei.wang
 *
 */
@Component
public class AuthorizeInterceptor implements HandlerInterceptor {
	
	private static Logger logger = LoggerFactory.getLogger(AuthorizeInterceptor.class);

	@Autowired
	private H5Authenticator authenticate;

	@Autowired
	private IAuthorize authorize;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		if(isSkip(request)){
			return true;
		}
		// 验证token
		String token = request.getParameter(IAuthenticate.LOGIN_TOKEN);
		if (StringUtils.isBlank(token)) {
			token = request.getHeader(IAuthenticate.LOGIN_TOKEN);
		}

		if (StringUtils.isBlank(token)) {
			logger.info("请求url：{}，没有获取到token值",request.getRequestURI());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			response.getWriter().write(Result.error(HttpStatus.SC_UNAUTHORIZED + "", "请重新登陆。").toString());
			return false;
		}
		if (!authenticate.isLogin(token)) {
			logger.info("请求url：{}，token失效",request.getRequestURI());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			response.getWriter().write(Result.error(HttpStatus.SC_UNAUTHORIZED + "", "请重新登陆。").toString());
			return false;
		}
		LoginSession loginSession = authenticate.getLoginSession(token);
		if (loginSession == null) {
			logger.info("请求url：{}，系统错误。",request.getRequestURI());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			response.getWriter().write(Result.error(HttpStatus.SC_BAD_REQUEST + "", "系统错误。").toString());
		}

		boolean accessAllowed = authorize.isAccessAllowed(request.getRequestURI(), loginSession);
		if (accessAllowed) {
			return true;
		} else {
			logger.info("请求url：{},用户：{},权限：{}",request.getRequestURI(),loginSession.getInfo().getAcctId(),loginSession.getPermissions());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			response.getWriter().write(Result.error(HttpStatus.SC_UNAUTHORIZED + "", "权限不足").toString());
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	/**
	 * 是否跳过一些不需要权限认证的请求。
	 * 
	 * @return boolean
	 */
	private boolean isSkip(HttpServletRequest request) {
		if (request.getRequestURI().contains("/dealer/reg/audit")) {
			return true;
		}
		if (request.getRequestURI().contains("/shop/reg/audit")) {
			return true;
		}
		if (request.getRequestURI().contains("/rebate/dealers/v2/api/login/type/")) {
			return true;
		}

		if (request.getRequestURI().contains("/rebate/shop/api/regist")) {
			return true;
		}

		if (request.getRequestURI().contains("/h5/")) {
			return true;
		}
		
		// 如果是登录就放行
		if (request.getRequestURI().matches("^/(ins|rebate)/.*(?<!sms)/(login|vercode|)(/v2)?$")) {
			return true;
		}
		if (request.getRequestURI().matches("^/rebate/dealers/api/info$")) {
			return true;
		}
		if (request.getRequestURI().matches("^/rebate/regist/api/(query|regist)$")
				|| request.getRequestURI().startsWith("/open/")) {
			return true;
		}
		
		//登出
		if (request.getRequestURI().matches("^/(ins|rebate)/.*/logout$")) {
			return true;
		}
		
		//跳过api（别的服务）调用接口
		if (request.getRequestURI().contains("/open/dealer/reg/regist")) {
			return true;
		}
		if (request.getRequestURI().contains("/open/dealer/reg/validate")) {
			return true;
		}
		if (request.getRequestURI().contains("/open/rebate/regist/api/query")) {
			return true;
		}
		if (request.getRequestURI().contains("/open/rebate/regist/api/regist")) {
			return true;
		}
		
		// 如果是短信验证码就通过token跟eseId来验证
		if ("/rebate/api/sms/vercode".equals(request.getRequestURI())) {
			return true;
		}
		
		// 注册放行
		if ("/api/dealer/reg/regist".equals(request.getRequestURI())) {
			return true;
		}
		
		if ("/api/dealer/reg/validate".equals(request.getRequestURI())) {
			return true;
		}
		if ("/rebate/shop/api/save".equals(request.getRequestURI())) {
			return true;
		}
		//util 修正数据
		if (request.getRequestURI().contains("/util/location/shop/relocation/esecode/")) {
			return true;
		}

		
		return false;
	}

}
